package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.MemberInfo;
import com.itheima.service.MemberService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 会员管理
 */

@RestController
@RequestMapping("/member")
public class MemberController {

    @Reference//查找服务
    private MemberService memberService;

    //新增会员
    @RequestMapping("/add")
    public Result add(@RequestBody Member member) {
        //检测手机号唯一
        Member member1 = memberService.findByTel(member.getPhoneNumber());
        //检测档案号唯一
        Member member2 = memberService.findByFileNumber(member.getFileNumber());
        if (member2 != null) {
            return new Result(false, "档案号已被使用");
        }
        if (member1 == null) {
            try {
                member.setRegTime(new Date());
                memberService.add(member);
            } catch (Exception e) {
                e.printStackTrace();
                //服务调用失败
                return new Result(false, MessageConstant.ADD_MEMBER_FAIL);
            }
            return new Result(true, MessageConstant.ADD_MEMBER_SUCCESS);
        } else {
            return new Result(false, "此号码已被注册");
        }

    }

    //会员档案分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = memberService.pageQuery(queryPageBean);
        return pageResult;
    }


    //删除
    @PreAuthorize("hasAuthority('CHECKITEM_DELETE')")//权限校验
    @RequestMapping("/delete")
    public Result delete(Integer id) {
        //查询当前会员是否有预约信息, 根据当前会与那id查询订单id
        List<Integer> list = memberService.findOrderByMemId(id);
        if (list.size() > 0) {
            //有,不能删除
            return new Result(false, "当前会员含有预约信息, 无法删除");
        } else {
            //没有, 进行删除
            try {
                memberService.deleteById(id);
            } catch (Exception e) {
                e.printStackTrace();
                //服务调用失败
                return new Result(false, MessageConstant.DELETE_MEMBER_FAIL);
            }
            return new Result(true, MessageConstant.DELETE_MEMBER_SUCCESS);
        }
    }


    //编辑
    @RequestMapping("/edit")
    public Result edit(@RequestBody Member member) {
        //检测手机号唯一
        Member member1 = memberService.findByTel(member.getPhoneNumber());
        //检测档案号唯一
        Member member2 = memberService.findByFileNumber(member.getFileNumber());
        if (member2 != null) {
            if (!member2.getId().equals(member.getId()))
            return new Result(false, "档案号已被使用");
        }

        if (member1 == null || member1.getId().equals(member.getId())) {
            try {
                memberService.edit(member);
            } catch (Exception e) {
                e.printStackTrace();
                //服务调用失败
                return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
            }
            return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS);
        } else {
            return new Result(false, "此号码已经被使用");
        }
    }


    //回显
    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            Member member = memberService.findById(id);
            return new Result(true, MessageConstant.QUERY_MEMBER_SUCCESS, member);
        } catch (Exception e) {
            e.printStackTrace();
            //服务调用失败
            return new Result(false, MessageConstant.QUERY_MEMBER_FAIL);
        }
    }

    @RequestMapping("/findAll")
    public Result findAll() {
        try {
            List<Member> list = memberService.findAll();
            return new Result(true, MessageConstant.QUERY_MEMBER_SUCCESS, list);
        } catch (Exception e) {
            e.printStackTrace();
            //服务调用失败
            return new Result(false, MessageConstant.QUERY_MEMBER_FAIL);
        }
    }

    //批量导出
    @RequestMapping("/batchDownload")
    public void batchDownload(Integer[] ids, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //根据文件的路径获取编译后的路径
        //获取该文件的服务器访问路径（这里需要传入webapp下，你文件的路径，生成服务器访问路径）

        List<MemberInfo> list = memberService.findByIds(ids);
        System.out.println(list);
        //获得Excel模板文件绝对路径
        String templateRealPath = request.getSession().getServletContext().getRealPath("template") +
                File.separator + "batchDownload.xlsx";
        //读取模板文件创建Excel表格对象
        XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(templateRealPath)));
        XSSFSheet sheet = workbook.getSheetAt(0);
        XSSFRow row = null;

        int rowNum = 1;
        for (MemberInfo memberInfo : list) {
            row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(memberInfo.getName());
            row.createCell(1).setCellValue(memberInfo.getSex());//性别
            row.createCell(2).setCellValue(memberInfo.getPhoneNumber());//手机号
            row.createCell(3).setCellValue(memberInfo.getOrderDate());//日期
            row.createCell(4).setCellValue(memberInfo.getAddress());//地址
            row.createCell(5).setCellValue(memberInfo.getSetmealName());//套餐
            row.createCell(6).setCellValue(memberInfo.getCgName().toString());//检查组
            row.createCell(7).setCellValue(memberInfo.getCkName().toString());//检查项
        }
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("content-Disposition", "attachment;filename=memberDocument.xlsx");
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
        workbook.close();

    }
}
